<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { RoleDto } from '#/api/abp/role/types';

import { computed } from 'vue';

import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';
import { getPopupContainer } from '@vben/utils';

import {
  Dropdown,
  Modal,
  Popconfirm,
  Space,
  Button
} from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import { deleteRole, getRoles } from '#/api/abp/role';

import { columns, querySchema } from './data';
import roleModal from './role-modal.vue'; // Changed from roleDrawer
import rolePermissionModal from './role-permission-modal.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    checkMethod: ({ row }) => !row.isStatic,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getRoles({
          skipCount: (page.currentPage - 1) * page.pageSize,
          maxResultCount: page.pageSize,
          filter: formValues.filter,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'abp-role-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});



const [RoleModal, modalApi] = useVbenModal({
  connectedComponent: roleModal,
});

function handleAdd() {
  modalApi.setData({}); // Changed from drawerApi.setData
  modalApi.open(); // Changed from drawerApi.open
}

async function handleEdit(record: RoleDto) {
  modalApi.setData({ id: record.id }); // Changed from drawerApi.setData
  modalApi.open(); // Changed from drawerApi.open
}

async function handleDelete(row: RoleDto) {
  await deleteRole(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: RoleDto) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await Promise.all(ids.map(id => deleteRole(id)));
      await tableApi.query();
    },
  });
}

const { hasAccessByCodes } = useAccess();

const [RolePermissionModal, permissionModalApi] = useVbenModal({
  connectedComponent: rolePermissionModal,
});

function handlePermissionEdit(record: RoleDto) {
  permissionModalApi.setData({ name: record.name });
  permissionModalApi.open();

}

</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="角色列表">
      <template #toolbar-tools>
        <Space>
          <Button v-if="hasAccessByCodes(['AbpIdentity.Roles.Delete'])" :disabled="!vxeCheckboxChecked(tableApi)" danger
            type="primary" @click="handleMultiDelete">
            {{ $t('pages.common.delete') }}
          </Button>
          <Button v-if="hasAccessByCodes(['AbpIdentity.Roles.Create'])" type="primary" @click="handleAdd">
            {{ $t('pages.common.add') }}
          </Button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <Button v-if="hasAccessByCodes(['AbpIdentity.Roles.Update'])" class="ml-2" size="small" type="link"
            :ghost="true" @click="handlePermissionEdit(row)">
            {{ $t('pages.common.authorized') }}
          </Button>
          <Button v-if="hasAccessByCodes(['AbpIdentity.Roles.Update'])" class="ml-2" size="small" type="primary" :ghost="true" @click.stop="handleEdit(row)">
            {{ $t('pages.common.edit') }}
          </Button>
          <Popconfirm v-if="!row.isStatic" :get-popup-container="getPopupContainer" placement="left" title="确认删除？"
            @confirm="handleDelete(row)">
            <Button v-if="hasAccessByCodes(['AbpIdentity.Roles.Delete'])" class="ml-2" size="small" type="primary"
              :ghost="true" :danger="true" @click.stop="">
              {{ $t('pages.common.delete') }}
            </Button>
          </Popconfirm>

        </Space>

      </template>
    </BasicTable>
    <RoleModal @reload="tableApi.query()" />
    <RolePermissionModal @reload="tableApi.query()" />
  </Page>
</template>
